import axios from 'axios'
import safe from './webSecurity'
import base from './base'

const CancelToken = axios.CancelToken
const source = CancelToken.source()

let http = ''
let needVerify = false
let isVerify = false

// // 监听浏览器关闭
// document.addEventListener('visibilitychange', function() {
//   if (document.visibilityState == 'hidden') {
//     console.log(document.visibilityState)
//   }
// })

// 创建http请求实例
function httpCreate() {
  let _http = axios.create({
    timeout: 50000,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + localStorage.getItem('token') || null
    }
  })

  _http.defaults.baseURL = process.env.NODE_ENV === 'production'
    ? base.API_PROD
    : base.API_DEV

  // 添加请求拦截器 判断登录状态
  _http.interceptors.request.use(function(config) {
    if (!isVerify && needVerify) {
      httpCancel()
      window.location.href = 'login.html'
    } else {
    }

    return config
  })

  // 添加响应拦截器 过滤返回信息
  _http.interceptors.response.use(function(response) {
    return response.data
  })
  return _http
}

function httpCancel() {
  source.cancel('httpCancel')
}

function Post(url, data, config) {
  isVerify = sessionStorage.getItem('tokenInfo') ? true : false

  // 当没有data参数时
  if (data && !config) config = data

  // 过滤xss攻击
  if (!(config && config.headers && (config.headers['Content-Type'] = 'multipart/form-data'))) {
    data = safe.xss(JSON.stringify(data))
  }

  // 创建实例 配置参数
  http = httpCreate()
  Object.keys(config).forEach(key => {
    typeof http.defaults[key] != 'object'
      ? http.defaults[key] = config[key]
      : http.defaults[key] = Object.assign(http.defaults[key], config[key])
  })

  needVerify = config.needVerify === true ? true : false
  http = (function() {
    return http.post(url, data, {
      cancelToken: source.token
    })
  })()

  return http

  // httpReCall(http, foo)
}

function Get(url, params) {
  // 过滤xss攻击
  let paramsTransform = {}
  if (params) {
    Object.keys(params).forEach(key => {
      paramsTransform[key] = '' + safe.xss(params[key])
    })
  }

  http = (function() {
    return httpCreate().get(url, {
      params: paramsTransform,
      cancelToken: source.token
    })
  })()

  return http
  // httpReCall(http, foo)
}

export default {
  post: Post,
  get: Get
}
